const Router = require('koa-router');
const router = new Router();
const tools = require('../tools/tool') 
const pageParams = require("../tools/cols");
const {db, QueryTypes,Op,DataTypes} = require("../models/db");
const tool = require("../tools/tool");
const xe = require("xe-utils");
// 表格列
router.post('/page/columns', async ctx => {
    let sets = pageParams(ctx, tools)
    if(!sets) return ctx.err('没有数据模型')
    sets = tools.obj2str(sets.form)
    return ctx.suc('', sets)
})
// 删除
router.post('/page/del', async ctx => {
    let id = ctx.request.body.id;
    let tenantId = ctx.user.tenantId;
    let par = await tools.pageSets(ctx)
    if(par.formMod) {
        await tools.beforeAction(par, ctx)
        // let attr = db.models[form.mod].getAttributes()
        let delLimit = ''
        if(par.delLimit) {
            delLimit = tools.str2obj(par.delLimit)
        }
        if(delLimit) {
            for (let i = 0; i < delLimit.length; i++) {
                if(delLimit[i].mod && delLimit[i].field) {
                    let where = {
                        tenantId: ctx.user.tenantId,
                    }
                    where[delLimit[i].field] = id
                    let c = await db.models[delLimit[i].mod].count({
                        where,
                    })
                    if (c > 0) {
                        return ctx.err('已使用,不能删除')
                    }
                }
            }
        }
        let where = {
            id
        }
        let attrs = db.models[par.formMod].getAttributes()
        if(typeof attrs.tenantId !== 'undefined') {
            where.tenantId = tenantId
        }
        await db.models[par.formMod].destroy({
            where
        })
        return ctx.suc('已删除')
    }
    else {
        return ctx.err('没有找到数据模型名称')
    }
})
// 新增取得表彰配置
router.post('/page/getEditRule', async ctx => {
    let sets = await tools.pageSets(ctx)

    let editRule = [
        {field: 'id', hide: true}
    ]
    sets.fields.map(row => {
        if(row.add || row.edit) {
            let rule = {
                field: row.field,
                title: row.title,
                clearable: true
            }
            if(row.component && row.add) {
                rule.com = row.component
                if(row.component === 'JAuto') {
                    if(row.idField) rule.idField = row.idField
                    if (row.list) {
                        rule.list = tools.str2obj(row.list)
                    }
                    else {
                        rule.cat = row.cat
                    }
                }
                if(row.component === 'JSelectTree') {
                    if(row.idField) rule.idField = row.idField
                    if (row.list) {
                        rule.list = tools.str2obj(row.list)
                    }
                    else {
                        rule.cat = row.cat
                    }
                }
                if(row.component === 'JSelect') {
                    if(row.idField) rule.idField = row.idField
                    if (row.list) {
                        rule.list = tools.str2obj(row.list)
                    }
                    else {
                        rule.cat = row.cat
                    }
                }

                if(row.component === 'JCheck') {
                    rule.falseLabel = 0
                    rule.trueLabel = 1
                }
                if(row.required) {
                    rule.required = true
                }
                if(row.default) {
                    if(typeof row.vartype === 'number') {
                        rule.value = tools.xe.toNumber(row.default)
                    }
                    else if (row.component === 'JPicker') {
                        rule.value = tools.getDay('', tools.xe.toNumber(row.default))
                    }
                    else {
                        rule.defaultValue = row.default
                    }
                }

                editRule.push(rule)
            }
        }
    })
    delete sets.fields
    delete sets.pageRule
    delete sets.rowBtn
    delete sets.delLimit
    delete sets.id
    delete sets.sqls
    delete sets.orderby
    delete sets.detailGrid
    return ctx.suc('', {
        ...sets,
        rule: tools.obj2str(editRule)
    })
})
// 获取表单设置
router.post('/page/getEditFormRule', async ctx => {
    let sets = await tools.pageSets(ctx)
    let editRule = [
        {field: 'id',  hide: true}
    ]
    let tenantId = ctx.user.tenantId;
    switch (ctx.request.body.whichPage) {
        case 'inventoryInit': {
            let storate = await db.models['storage'].findOne({
                where: {
                    tenantId
                }
            })
            if(!storate) return ctx.err('没有设置默认仓库')
            editRule.push({
                field: 'locationId',  hide: true,value: storate.id
            })
            editRule.push({
                field: 'invId',  hide: true
            })
            editRule.push({
                field: 'locationName',title: '仓库',type: 'JAuto', props:{cat: 'location'},effect: {required: true}, value: storate.name,
                inject: true,
                on: {
                    change (inject, val) {
                        inject.$f.setValue('locationId', val ? val.id : null)
                    }
                }
            })
            editRule.push({
                field: 'invName',title: '商品',type: 'JAuto', props:{cat: 'goods'},effect: {required: true},
                inject: true,
                on: {
                    change (inject, val) {
                        inject.$f.setValue('invId', val ? val.id : null)
                    }
                }
            })
            editRule.push({
                field: 'qty1',title: '数量(大)',type: 'InputNumber',props:{precision: 0,min: 0}
            })
            editRule.push({
                field: 'qty2',title: '数量(小)',type: 'InputNumber', props:{precision: 0,min: 0}
            })
            editRule.push({
                field: 'amount',title: '期初金额',type: 'InputNumber',props:{precision: 2,min: 0}
            })
        } break
        default: {
            sets.fields.map(row => {
                if(row.add || row.edit) {
                    let rule = {
                        field: row.field,
                        title: row.title,
                        props: {
                            clearable: true
                        }
                    }
                    if(row.component && row.add) {
                        rule.com = row.component
                        let idField = row.idField
                        if(idField) {
                            editRule.push({
                                com: 'hidden',
                                field: idField
                            })
                            let objStr = `{change:(inject,val)=>{
                        setTimeout(()=>{inject.$f.setValue('${idField}', val ? val.id : null);},10)
                    } }`
                            rule.inject = true
                            rule.on = tools.str2obj(objStr)
                        }
                        if(row.component === 'jauto' || row.component === 'JAuto') {
                            rule.com = 'JAuto'
                            if (row.list) {
                                rule.props.list = tools.str2obj(row.list)
                            }
                            else {
                                rule.props.cat = row.cat
                            }
                        }
                        if(row.component === 'TAuto') {
                            rule.com = 'TAuto'
                            if (row.list) {
                                rule.props.list = tools.str2obj(row.list)
                            }
                            else {
                                rule.props.cat = row.cat
                            }
                        }
                        if(row.component === 'JSelectTree') {
                            rule.com = 'JSelectTree'
                            if (row.list) {
                                rule.props.list = tools.str2obj(row.list)
                            }
                            else {
                                rule.props.cat = row.cat
                            }
                        }
                        if(row.component === 'JSelect') {
                            rule.com = 'JSelect'
                            if (row.list) {
                                rule.props.list = tools.str2obj(row.list)
                            }
                            else {
                                rule.props.cat = row.cat
                            }
                        }
                        if(row.component === 'jinput') {
                            rule.com = 'ltext'
                        }
                        if(row.component === 'jcheck') {
                            rule.com = 'JCheck'
                            rule.props.falseLabel = 0
                            rule.props.trueLabel = 1
                        }
                        if(row.required) {
                            rule.effect = {required: true}
                        }
                        if(row.default) {
                            if(typeof row.vartype === 'number') {
                                rule.value = tools.xe.toNumber(row.default)
                            }
                            else if (row.component === 'JPicker') {
                                rule.value = tools.getDay('', tools.xe.toNumber(row.default))
                            }
                            else {
                                rule.value = row.default
                            }
                        }
                        if(row.span) {
                            rule.col = {
                                span: tools.xe.toNumber(row.span)
                            }
                        }
                        editRule.push(rule)
                    }
                }
                if(row.field && row.default) {
                    editRule.push({
                        field: row.field,
                        hide: true,
                        value: row.vartype === 'number' ? tools.xe.toNumber(row.default) : row.default
                    })
                }
            })
        } break
    }

    return ctx.suc('', {
        saveUrl: sets.saveUrl,
        rule: tools.obj2str(editRule)
    })
})
// 搜索表单规则
router.post('/page/getGridColumns', async ctx => {
    let obj = await tools.pageSets(ctx)
    let  sets = tools.getFields(obj)
    let detailGrid = obj.detailGrid ? tools.str2obj(obj.detailGrid) : []
    let fields = sets.fields
    return ctx.suc('', {
        listUrl: obj.listUrl,
        saveUrl: obj.saveUrl,
        delUrl: obj.delUrl,
        hideFooter: obj.hideFooter,
        hidePage: obj.hidePage,
        fields: tools.obj2str(fields),
        detailGrid
    })
})
const getRouteByBillNo = async (billNo, tenantId) => {
    if(billNo.indexOf('PZ') === 0) {
        return 'card'
    }
    else {
        let invoice = await db.models['invoice'].findOne({
            where: {
                tenantId,
                billNo
            }
        })
        if(invoice.billType === 'RECEIPT') {
            return 'receipt'
        }
        if(invoice.billType === 'PAYMENT') {
            return 'payment'
        }
        if(invoice.transType === 150601) {
            return 's-in'
        }
        if(invoice.transType === 150602) {
            return 's-out'
        }
        if(invoice.transType === 150603) {
            return 's-t'
        }
        if(invoice.transType === 150101) {
            return 'payment'
        }
        if(invoice.transType === 150706) {
            return 'oin'
        }
        if(invoice.transType === 150806) {
            return 'oout'
        }
        if(invoice.transType === 150501) {
            return 'pur-in'
        }
        if(invoice.transType === 150502) {
            return 'pur-out'
        }
        if(invoice.billType === 'YSK') {
            return 'yusk'
        }
        if(invoice.billType === 'YFK') {
            return 'yufk'
        }
        if(invoice.billType === 'YSG') {
            return 'yussp'
        }
        if(invoice.billType === 'SR') {
            return 'sr'
        }
        if(invoice.billType === 'YF') {
            return 'ysk'
        }
        if(invoice.billType === 'YS') {
            return 'yfk'
        }
        if(invoice.billType === 'ZZ') {
            return 'banktran'
        }
        if(invoice.billType === 'ZC') {
            return 'zc'
        }
        if(invoice.billType === 'YS2YS' || invoice.billType === 'YF2YF') {
            return 'hx'
        }
    }
    return false
}
// 删除
router.post('/page/getRouteByField', async ctx => {
    let field = ctx.request.body.field;
    let routeName = ctx.request.body.routeName;
    let value = ctx.request.body.value;
    let row = ctx.request.body.row;
    let tenantId = ctx.user.tenantId
    if(!field) return ctx.err('没有模型名')
    let route = {
        name: ''
    }
    if(field === 'billNo' || field === 'srcBillNo' || field === 'sourceBillNo') {
        route.name += await getRouteByBillNo(value, tenantId)
        route.query = {
            billNo: value,
            field,
            page: routeName,
            id: row.id
        }
        route.title = '单据'
    }
    // 往来欠款表点击明细路由
    if(routeName === 'qkb') {
        if(field === 'yfYe') {
            route.name = 'gysdzd'
        }
        if(field === 'ysYe') {
            route.name = 'khdzd'
        }
        if(field === 'yusYe') {
            route.name = 'ysdk'
        }
        if(field === 'yufYe') {
            route.name = 'yfdk'
        }
    }
    // 科目余额明细
    if(routeName === 'kmye') {
        if(field === 'price1') {
            route.title = '借方发生'
        }
        if(field === 'price2') {
            route.title = '贷方发生'
        }
        route.name = route.name + 'kmyemx'
        route.page = 'kmyemx'
        route.query = row
    }
    return ctx.suc('', route)
})
router.post('/page/getSalesByBuId', async ctx => {
    let buId = ctx.request.body.buId
    let invoidc = await db.query(`
     select id,name from admin where id in(select DISTINCT salesId from invoice where buId=${buId} and tenantId=${ctx.user.tenantId})
     `,{type: QueryTypes.SELECT})
    return ctx.suc('', invoidc)
})
// 搜索表单规则
router.post('/list/getSearchRule', async ctx => {
    if(!ctx.request.body.whichPage) return ctx.suc('')
    let obj = await tools.pageSets(ctx)

    let  fields = tools.getFields(obj)

    return ctx.suc('', tools.obj2str(fields.searchFields))
})
// ----------------------------new beg
router.post('/page/getPageRule', async ctx => {
    let body = ctx.request.body
    let whichPage = body.whichPage
    if (whichPage) {
        let page = await tool.pageSets(ctx)
        delete page.sqls
        delete page.orderby
        delete page.groupby
        let search = combPageRule(page)
        page.searchRule = search.searchRule
        page.fields = search.listFields

        return ctx.suc('', JSON.stringify(page))
    }

    return ctx.suc('', [])
})
const combPageRule = (obj) => {
    let fields = [

    ]
    if(obj.fields) {
        // fields.push({type: 'index', width: 50, fixed: 'left'},)
    }
    // if(!obj.hideCheckbox) {
    //     fields.push({type: 'selection', width: 40, fixed: 'left',align: 'center'})
    // }
    if(obj.fields) {
        obj.fields.map(col => {
            if(col.visible) {
                // if(col.filter) {
                //     col.filterRender = {name: 'FExtend'}
                //     col.filters = [{data: {vals: [], sVal: '', fMenu: '', f1Type:'', f1Val: '', fMode: 'and', f2Type: '', f2Val: ''}}]
                // }
                col.headerAlign = 'center'
                fields.push(col)
            }
        })
    }

    // 搜索组件规则
    let searchFields = []
    if(obj.fields) {
        obj.fields.map(row => {
            if(row.condition && row.field !== 'billState') {
                if(row.field && row.component) {
                    let rule = {
                        field: row.field,
                        title: row.title,
                        clearable: true,
                        cat: row.cat,
                        width: 230
                    }
                    if(row.component) {
                        rule.com = row.component
                        if(row.default) {
                            if(typeof row.vartype === 'number') {
                                rule.defaultValue = tool.xe.toNumber(row.default)
                            }
                            else if (row.component === 'JPicker') {
                                rule.defaultValue = tool.getDay('', tool.xe.toNumber(row.default))
                            }
                            else {
                                rule.defaultValue = row.default
                            }
                        }
                        if(row.idField) {
                            rule.idField = row.idField
                        }
                        // if(row.component === 'JAuto') {
                        //
                        //     // let objStr = `{change:(inject,val)=>{
                        //     //     setTimeout(()=>{inject.$f.setValue('${idField}', val ? val.id : null);},10)
                        //     // } }`
                        //     // rule.inject = true
                        //     // rule.on = tool.str2obj(objStr)
                        // }
                        if(row.list) {
                            rule.list = tool.str2obj(row.list)
                        }

                        searchFields.push(rule)
                    }

                }
            }
        })
    }
    return {
        listFields: fields,
        searchRule: searchFields
    }
}

//---------------------------------new end
const combSearch = (params, ctx) => {
    let cols = params.search.rule
    let formData = ctx.request.body.formData;
    let where = []
    if(formData.searchTxt) {
        let w = []
        cols.map(row =>　{
            if(row.quick) {
                w.push(`${row.field} like '%${formData.searchTxt}%'`)
            }
        })
        if(w.length > 0) {
            where.push(`(${w.join(' or ')})`)
        }
    }
    else {
        for (let i in formData) {
            if (i && typeof formData[i] !== 'undefined' && formData[i] !== null && formData[i] !== '') {
                cols.map(s => {
                    if (s.field === i && s.op) {
                        if(tools.xe.indexOf(params.sql, '$'+s.field) !== -1) {
                            params.sql = params.sql.replaceAll('$'+s.field, formData[i])
                        }
                        else {
                            let w = s.op.replaceAll('$tid', ctx.user.tenantId)
                                .replaceAll('$uid', ctx.user.id)
                                .replaceAll('$', formData[i])
                            where.push(`${s.field} ${w}`)
                        }
                    }
                })
            }
        }
    }
    return where
}

router.post('/page/list', async ctx => {
    let whichPage = ctx.request.body.whichPage;
    let currentPage = ctx.request.body.currentPage ?ctx.request.body.currentPage:1;
    let pageSize = ctx.request.body.pageSize?ctx.request.body.pageSize:200;
    let excel = ctx.request.body.excel?ctx.request.body.excel:0;
    let sort = ctx.request.body.sort
    let offset = (currentPage - 1) * pageSize;
    if(!whichPage) return ctx.err('没有模型名')
    let params = pageParams(ctx, tools) // cols文件中的列配置
    let columns = params.columns
    let where = combSearch(params, ctx)
    let sql = params.sql
    if(where.length > 0) {
        sql = sql + ' and ' + where.join(' and ')
    }
    let orderBy = ''
    if(sort && sort.length > 0) {
        let ord = []
        sort.map(o => {
            ord.push(` ${o.field} ${o.order}`)
        })
        orderBy = ` order by ${ord.join(',')} `
    }
    else {
        orderBy = (params.order ? params.order : ' order by id desc ')
    }
    sql = sql.replaceAll('$tid', ctx.user.tenantId)
    sql = sql.replaceAll('$uid', ctx.user.id)
    if(excel) {
        sql += orderBy
        let ret = await db.query(sql, {type: QueryTypes.SELECT})
        return await tools.doExcelOut(ctx, ret, params)
    }
    else {
        let countModel = await db.query( `select count(*) count from (${sql}) a`, {type: QueryTypes.SELECT, plain: true} );
        let total = parseInt(countModel.count);
        // 默认分页
        sql += orderBy
        if(typeof params.allowPage === 'undefined' || params.allowPage) {
            sql += " offset " + offset + " rows fetch next " + pageSize + ' rows only; '
        }
        let ret = await db.query(sql, {type: QueryTypes.SELECT });
        return ctx.suc('', {
            total,
            list: ret,
            columns: tools.obj2str(columns)
        })
    }
})
router.post('/page/pageParams', async ctx => {
    let sets = pageParams(ctx, tools)
    if(!sets) return ctx.err('没有数据模型')
    sets.columns.map(row => {
        if(row.filter) {
            row.filterRender = {name: 'FExtend'}
            row.filters = [{data: {vals: [], sVal: '', fMenu: '', f1Type:'', f1Val: '', fMode: 'and', f2Type: '', f2Val: ''}}]
        }
    })
    sets.search.rule.map(row => {
        if(row.props) {
            row.props.clearable = true
        }
        else {
            row.props = {
                clearable: true
            }
        }
    })
    sets.form.rule.map(row => {
        if(row.props) {
            row.props.clearable = true
        }
        else {
            row.props = {
                clearable: true
            }
        }
    })
    sets = tools.obj2str(sets)
    return ctx.suc('', sets)
})
router.post('/page/psApiUrl', async ctx => {
    return ctx.suc('', 'https://v3.sanzhiyun.cn/#/deliver')
})

// 通用保存表单
const setFormData = async (modName, formData, ctx) => {
    let attrs = db.models[modName].getAttributes()
    for(let i in attrs) {
        if(i === 'tenantId') {
            formData.tenantId = ctx.user.tenantId
        }
        if(tools.xe.endsWith(i, 'Id')) {
            if(!formData[i]) formData[i] = null
        }
        if(i === 'pinYin') {
            formData.pinYin = formData.name ? tools.py(formData.name) : null
        }
        if(attrs[i].type.toString().includes('DECIMAL') || attrs[i].type.toString().includes('INTEGER')  || attrs[i].type.toString().includes('TINYINT')  ) {
            formData[i] = tools.xe.toNumber(formData[i])
        }
        if(i === 'code') {
            if(isTree(attrs) && !formData.id) {
                // 新增设置树形表的code
                await setCode(modName, formData, ctx.user.tenantId)
            }
        }
        if(i === 'pid') {
            await setPid(modName, formData, ctx.user.tenantId, attrs)
        }
        if(i === 'isInit') {
            formData.isInit = 0
        }
        if(i === 'ct') {
            if(!formData.id) formData.ct = tools.getTime()
        }
        if(i === 'ctime') {
            if(!formData.id) formData.ctime = tools.getTime()
        }
        if(i === 'ut') {
            formData.ut = tools.getTime()
        }
        if(i === 'utime') {
            formData.utime = tools.getTime()
        }
        if(i === 'cby') {
            if(!formData.id) formData.cby = ctx.user.id
        }
        if(i === 'uby') {
            formData.uby = ctx.user.id
        }
    }
    // 设置快速搜索内容
    hasQuick(attrs, formData)
}
// 如果有pid字段，视为是树形表结构
const isTree = (attrs) => {
    for(let i in attrs) {
        if(i === 'pid') return true
    }
    return false
}
const hasQuick = (attrs, formData) => {
    let quick = []
    for(let i in attrs) {
        if(i === 'quick') {
            for(let i in formData) {
                if(formData[i]) {
                    quick.push(formData[i])
                }
            }
        }
    }
    if(quick.length > 0) formData.quick = quick.join(',')
    return false
}
// 检测索引
const checkIndex = async (modName, ctx) => {
    // 通过返回false  错误返回错误信息
    let indexes = db.models[modName].getIndexes()
    let formData = ctx.request.body.formData;
    // 检测索引
    if(indexes.length > 0) {
        for (let x = 0; x < indexes.length; x++) {
            let row = indexes[x]
            if(row.unique) {
                let where = {}
                let hastent = false
                for (let i = 0; i < row.fields.length; i++) {
                    if(row.fields[i] === 'tenantId') {
                        hastent = true
                    }else {
                        // 如果索引中的字体有上传的值
                        if(typeof row.fields[i] !== 'undefined' && formData[row.fields[i]])
                            where[row.fields[i]] = formData[row.fields[i]]
                    }
                }
                if(!tools.xe.isEmpty(where)) {
                    if(hastent) where.tenantId = ctx.user.tenantId
                }
                if (formData.id) {
                    if(!tools.xe.isEmpty(where)) {
                        where.id = {
                            [Op.ne]: formData.id
                        }
                    }
                }
                if(!tools.xe.isEmpty(where)) {
                    let c = await db.models[modName].count({
                        where: where
                    })
                    if(c > 0) {
                        throw Error(row.name)
                    }
                }
            }
        }
    }
}
// 设置树形编码
const setCode = async ( mod, formData, tenantId) => {
    if(!formData.id) {
        if(typeof formData.pid !== 'undefined') {
            if(formData.pid) {
                let last = await db.models[mod].findOne({
                    where: {
                        tenantId,
                        pid: formData.pid
                    },
                    order: [['code', 'desc']]
                })
                let lastModel = await db.models[mod].findOne({
                    where: {
                        tenantId,
                        id: formData.pid
                    }
                })
                let code = ''
                if(last) {
                    code = tools.xe.toNumber(last.code) + 1
                }
                else {
                    code = lastModel.code + '10'
                }
                if(tools.xe.toNumber(code) === 99) {
                    throw Error('最多90个分类')
                }
                formData.code = tools.xe.toString(code)
            }
            else {
                if(formData.pidName) {
                    let where  = {
                        tenantId,
                        name: formData.pidName
                    }
                    if(typeof formData.typeNumber !== 'undefined' && formData.typeNumber) {
                        where.typeNumber = formData.typeNumber
                    }
                    let pidModel = await db.models[mod].findOne({
                        where: where
                    })
                    let last = await db.models[mod].findOne({
                        where: {
                            tenantId,
                            pid: pidModel.id
                        },
                        order: [['code', 'desc']]
                    })
                    let code = ''
                    if(last) {
                        code = tools.xe.toNumber(last.code) + 1
                    }
                    else {
                        code = pidModel.code + '10'
                    }
                    if(tools.xe.toNumber(code) === 99) {
                        throw Error('最多90个分类')
                    }
                    formData.code = tools.xe.toString(code)
                }
                else {
                    let last = await db.models[mod].findOne({
                        where: {
                            tenantId
                        },
                        order: [['code', 'desc']]
                    })
                    let code = '10'
                    if(last) {
                        code = tools.xe.toNumber(last.code) + 1
                    }
                    if(tools.xe.toNumber(code) === 99) {
                        throw Error('最多90个分类')
                    }
                    formData.code = tools.xe.toString(code)
                }
            }
        }
    }
}
// 设置本列属性的父类值
const setPid = async ( mod, formData, tenantId, attrs) => {
    if(!formData.id) {
        if(typeof formData.pid !== 'undefined') {
            if(formData.pid) {
                let pidModel = await db.models[mod].findOne({
                    where: {
                        tenantId,
                        id: formData.pid
                    }
                })
                for(let i in attrs) {
                    if(i === 'pidCode') {
                        formData.pidCode = pidModel.code
                    }
                    if(i === 'fullName') {
                        formData.fullName = pidModel.name + '_' + formData.name
                    }
                    if(i === 'direct') {
                        formData.direct = pidModel.direct
                    }
                }
            }
            else {
                if(formData.pidName) {
                    let where  = {
                        tenantId,
                        name: formData.pidName
                    }
                    if(typeof formData.typeNumber !== 'undefined' && formData.typeNumber) {
                        where.typeNumber = formData.typeNumber
                    }
                    let pidModel = await db.models[mod].findOne({
                        where: where
                    })
                    formData.pid = pidModel.id
                    for(let i in attrs) {
                        if(i === 'pidCode') {
                            formData.pidCode = pidModel.code
                        }
                        if(i === 'fullName') {
                            formData.fullName = pidModel.name + '_' + formData.name
                        }
                        if(i === 'direct') {
                            formData.direct = pidModel.direct
                        }
                    }
                }
            }
        }
    }
}

// 表单保存
router.post('/page/saveForm', async ctx => {
    let formData = ctx.request.body.formData;
    let whichPage = ctx.request.body.whichPage?ctx.request.body.whichPage:'';
    let sets = await tools.pageSets(ctx)
    let tenantId = ctx.user.tenantId
    let mod = sets.formMod
    let id = formData.id
    switch (whichPage) {
        // 保存期初
        case 'inventoryInit':{
            let good = await db.models['goods'].findOne({
                where: {
                    tenantId,
                    id: formData.invId
                }
            })
            if(!good) return ctx.err('此商品档案错误')
            let qty = tools.xe.add(tools.xe.multiply(formData.qty1,good.spec),formData.qty2)
            let initGoodsModel;
            if(id) {
                initGoodsModel = await db.models['initGoods'].findOne({
                    where: {
                        tenantId,
                        id
                    }
                })
                if(!initGoodsModel) return ctx.err('修改失败')
                initGoodsModel.uby = ctx.user.id
                initGoodsModel.utime = tools.getTime()
                if(initGoodsModel.invId != formData.invId) return ctx.err('不能更换商品')
                let start = await tools.zqIsStart(tenantId);
                if(start) {
                    let hasBiz = await db.models['invoiceInfo'].count({
                        where:{
                            tenantId,
                            invId: formData.invId,
                        }
                    })
                    if(tools.xe.toNumber(initGoodsModel.qty1) != tools.xe.toNumber(formData.qty1)) {
                        if(hasBiz) return ctx.err('已产生业务数据,不能再修改期初数量')
                    }
                    if(tools.xe.toNumber(initGoodsModel.qty2) != tools.xe.toNumber(formData.qty2)) {
                        if(hasBiz)  return ctx.err('已产生业务数据,不能再修改期初数量')
                    }
                    if(tools.xe.toNumber(initGoodsModel.amount) != tools.xe.toNumber(formData.amount)) {
                        if(hasBiz)  return ctx.err('已产生业务数据,不能再修改期初金额')
                    }
                }
            }
            else {
                initGoodsModel = db.models['initGoods'].build();
                initGoodsModel.cby = ctx.user.id
                initGoodsModel.ctime = tools.getTime()
            }
            initGoodsModel.tenantId = tenantId;
            initGoodsModel.locationId = formData.locationId;
            initGoodsModel.locationName = formData.locationName;
            initGoodsModel.invId = formData.invId;
            initGoodsModel.invName = formData.invName;
            initGoodsModel.unit = good.unit2?good.unit2:good.unit1;
            initGoodsModel.qty = qty;
            initGoodsModel.qty1 = formData.qty1;
            initGoodsModel.qty2 = formData.qty2;
            initGoodsModel.amount = formData.amount;
            await initGoodsModel.save();
            return ctx.suc('已保存')
        } break
        default: {
            if(mod) {


                await tools.beforeAction(sets, ctx)
                await checkIndex(mod, ctx)
                await setFormData(mod, formData, ctx)
                let model = null
                if(formData.id) {

                    let where = {
                        id: id
                    }
                    let attrs = db.models[mod].getAttributes()
                    if(typeof attrs.tenantId !== 'undefined') {
                        where.tenantId = tenantId
                    }
                    let old = await db.models[mod].findOne({
                        where
                    })
                    if(!old) {
                        return ctx.err('未查询到数据')
                    }
                    if(old.isInit) {
                        return ctx.err('不能修改初始设置数据')
                    }
                    await db.models[mod].update(formData, {
                        where
                    })
                    model = formData
                }
                else {
                    delete formData.id
                    model= await db.models[mod].create(formData)
                }
                return ctx.suc('保存成功', model)
            }
            else {
                return ctx.err('没有找到数据模型名称')
            }
        }
            break
    }
})



module.exports = router;